<template>
  <div>当前鼠标位置</div>
  <div>x: {{ mouse.x }}</div>
  <div>y: {{ mouse.y }}</div>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted, reactive } from 'vue'

// 定义响应式数据
const mouse = reactive({
  x: 0,
  y: 0,
})

// 🎯MouseEvent    鼠标事件对象的 TS 类型
const mouseFn = (e: MouseEvent) => {
  // 把鼠标坐标值赋值更新给响应式数据
  mouse.x = e.clientX
  mouse.y = e.clientY
}

onMounted(() => {
  // 全屏 document 添加鼠标移动事件监听
  document.addEventListener('mousemove', mouseFn)
})

// 组件卸载时，清理全局事件，性能优化
onUnmounted(() => {
  document.removeEventListener('mousemove', mouseFn)
})
</script>
